#include "plugin.h"
#include <QSettings>
#include <QDir>

Plugin::Plugin(QObject *parent) : QObject(parent),mWidget(nullptr),process(nullptr)
{

}

Plugin::~Plugin()
{

}

//因为dll文件执行的时候，并不知道自己的路径，获取的也是app的路径
//参数为dll文件的路径
void Plugin::setConfig(QString conf)
{
    mConfigPath = conf.mid(0,conf.lastIndexOf("/"));    //获取插件路径
    setPluginConfig();//依据路径获取配置文件
}

QString Plugin::getName()
{
    if(mPluginName.isEmpty())
        return "未知插件";
    return mPluginName;
}

QIcon Plugin::getIcon()
{
    QString iconFile = mPluginIconImg;
    if(!QFile::exists(iconFile))
        iconFile = QString(":/new/prefix1/defaultIcon.png");
    QIcon icon(iconFile);
    return icon;
}

QWidget* Plugin::creactUi(QWidget *parent)
{
    Q_UNUSED(parent)
    //直接启动对应的exe文件，如果不存在则使用软件默认的弹窗提示
    if(QFile::exists(mPluginAppPath))
    {
        qDebug()<<Q_FUNC_INFO<<"run App:"<<mPluginAppPath;
        if(process)
            return nullptr;
        process = new QProcess;  //new一个进程对象
        process->setEnvironment(process->environment());
        process->start(mPluginAppPath);                 //启动并设置参数
        process->waitForStarted();
    }
    else
    {
        qDebug()<<Q_FUNC_INFO<<"App not exists:"<<mPluginAppPath;

    }
    return nullptr;
}

bool Plugin::deleteUi()
{
    //关闭该进程
    if(process)
        delete process;
    return 1;
}

bool Plugin::isOpenUi()
{
    //查询该进程
    return 1;
}

/***************************************
 * 配置文件名 plugin.conf / plugin.json
 * 插件名字：pluginName
 * 插件ICON：pluginIcon
 * 插件APP：pluginAppPath
 * *************************************/
void Plugin::setPluginConfig()
{
    QString path = mConfigPath;
    qDebug()<<Q_FUNC_INFO<<path;

    QSettings set(path + "/plugin.conf",QSettings::IniFormat);

    QString defaultName = path.mid(path.lastIndexOf("/") + 1);  //获取该插件的文件夹名字,用于默认插件名
    mPluginName = set.value("pluginName",defaultName).toString();

    QString defaultImg = path + "/pluginIcon.png";
    mPluginIconImg = set.value("pluginIcon",defaultImg).toString();

    QString defaultApp = path + "/pluginApp.exe";
    mPluginAppPath = set.value("pluginAppPath",defaultApp).toString();

    qDebug()<<Q_FUNC_INFO<<"mPluginName:"<<mPluginName<<endl
                        <<"mPluginIconImg:"<<mPluginIconImg<<endl
                        <<"mPluginAppPath:"<<mPluginAppPath;
}
